<?php

require_once("cLoginPhone.php");
require_once("cResultadoPhone.php");

class BykomClientePhone
{
	
	function getResultado($mysqli) {
		if ($rs = $mysqli->store_result()) {
       		if($rs->num_rows >0) {
    			$i=0;
				while ($finfo = $rs->fetch_field()) {
              	$campos[$finfo->name]=$i;
              	$i++;
				}
				while ($row = $rs->fetch_row()) $vec[] = $row;
				$rs->free_result();
				return new cResultado($campos, $vec);
       		}
			$mysqli->close();
		}
		return new cResultado();
	}
	/**********************************************************************/
	function LoginPhone($loginClass){
		$loginClassActual = $loginClass;
		$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
     		$loginClassActual->errorCode = 1;
       		return  $loginClassActual;
     	}
		$SQL = "SELECT * From aliasesphone a ";
		$SQL.= " WHERE a.alias ='". $loginClassActual->alias . "'";
		$SQL.= " AND a.clave ='". md5($loginClassActual->password) . "'";
		
	  	if (!$mysqli->real_query($SQL)) {
      	 	$loginClassActual->errorCode = 2;
       		return  $loginClassActual;
     	}
     	
     	$resultado = BykomClientePhone::getResultado($mysqli);
     	if ($resultado->cantidad() == 0) {
     		$loginClassActual->errorCode = 5;
       		return  $loginClassActual;
     	}
		$loginClassActual->tablaId = $resultado->campo('tablaId', 0);
		$loginClassActual->objetivo = $resultado->campo('objetivo', 0);
		$accessPhone = 0;
		if ($loginClassActual->objetivo == 4) { //Alias
			$SQL2 = " SELECT * From aliases a ";
			$SQL2.= " WHERE a.id ='". $loginClassActual->tablaId . "'";
			if (!$mysqli->real_query($SQL2)) {
	      	 	$loginClassActual->errorCode = 2;
	       		return  $loginClassActual;
	     	}
	     	$resultado2 = BykomClientePhone::getResultado($mysqli);
	     	$cuentaFK 	= $resultado2->campo("cuentaFk",0);
	     	$objetivoDB = $resultado2->campo("esFlota",0);
	     	$loginClassActual->objetivoDB = $objetivoDB;
	     	$loginClassActual->cuentaFk	  = $cuentaFK;
	     	$aliasId	= $loginClassActual->tablaId;
	     	$result = "";
	     	$realQuery = "";
	     	switch($objetivoDB){
	     		case 1: 
	     			if(BykomClientePhone::permisoAlias($aliasId,20)){
	     				$realQuery  = BykomClientePhone::getCuentasByAlias($aliasId,1);//tiene o no fijos asociados
	     				$result 	= BykomClientePhone::Cuentas_ClienteFijoAlias($aliasId);//tiene fijos asociados y con acceso por movil
	     			}
	     			if( ($realQuery!="" && $realQuery->cantidad()==0) && ($result != "" && $result->cantidad()==0)){
						$result = BykomClientePhone::Cuentas_Cliente($cuentaFK);
					}
	     			break;
	     		case 2:
	     			//no pregunto por el permiso HabilitarMovil porque es el unico movil que ve
	     				$result = BykomClientePhone::Cuentas_Cliente_Movil_BIS($cuentaFK);
	     			break;
	     		case 3:
					if(BykomClientePhone::permisoAlias($aliasId,21)){
						$result = BykomClientePhone::Cuentas_Cliente_Movil_FlotaAlias($aliasId);
					}
					if($result != "" && $result->cantidad()==0){
						$result = BykomClientePhone::Cuentas_Cliente_Movil_Flota($cuentaFK);
					}
	     			break;
	     		case 5:
			     	$result = BykomClientePhone::Cuentas_Cliente_Movil_DealerAlias($aliasId,$cuentaFK);
	     			break;
	     	}
	     	if($result != ""){
		     	$loginClassActual->cantidadSubCuentas = $result->cantidad();
	     	}else{
		     	$loginClassActual->cantidadSubCuentas = 0;
	     	}
	     	
	     	$SQL = "SELECT a.permisoMobile as accessPhone From aliases a";
		    $SQL.= " WHERE a.id =". $aliasId;
     		if (!$mysqli->real_query($SQL)) {
      	 		$loginClassActual->errorCode = 2;
       			return  $loginClassActual;
     		}
     		$resultado = BykomClientePhone::getResultado($mysqli);
     		$accessPhone = $resultado->campo('accessPhone',0);		
		}else if ($loginClassActual->objetivo == 1) { //Fijo
			$loginClassActual->objetivoDB = 1;
			$loginClassActual->cuentaFk	  = $loginClassActual->tablaId;
			//Verificacion de acceso a celular
			$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     		if (mysqli_connect_errno()) {
     			$loginClassActual->errorCode = 1;
       			return  $loginClassActual;
     		}
			$SQL = "SELECT abma.codigocl as codigocl, abma.ACCESS_PHONE as accessPhone From abmacodigos abma";
		    $SQL.= " WHERE abma.order_id =". $loginClassActual->tablaId;
		    if (!$mysqli->real_query($SQL)) {
      	 		$loginClassActual->errorCode = 2;
       			return  $loginClassActual;
     		}
     		$resultado = BykomClientePhone::getResultado($mysqli);
     		$accessPhone = $resultado->campo('accessPhone',0);
     		
     		$codigocl = $resultado->campo('codigocl',0);
     		//Busqueda de las subcuentas del fijo (solo fijas y con access phone habilitado)
     		$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     		if (mysqli_connect_errno()) {
     			$loginClassActual->errorCode = 1;
       			return  $loginClassActual;
     		}
     		$SQL = "SELECT abrl.order_id From abrlsubcuentas abrl";
     		$SQL.= " INNER JOIN abmacodigos abma ON abma.codigocl = abrl.codigocl";
		    $SQL.= " WHERE abrl.codigo_id = ". $codigocl . " AND abma.objetivo = 1 AND abma.ACCESS_PHONE = 1";
		    if (!$mysqli->real_query($SQL)) {
      	 		$loginClassActual->errorCode = 2;
       			return  $loginClassActual;
     		}
     		$resultado = BykomClientePhone::getResultado($mysqli);
     		$loginClassActual->cantidadSubCuentas = $resultado->cantidad() + 1;
		    
		} else if ($loginClassActual->objetivo == 3) { //Flota
			$loginClassActual->objetivoDB = 3;
			$loginClassActual->cuentaFk	  = $loginClassActual->tablaId;
			//Busqueda de todos los moviles de la flota
			$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     		if (mysqli_connect_errno()) {
     			$loginClassActual->errorCode = 1;
       			return  $loginClassActual;
     		}
			$SQL = "SELECT abma.order_id From abmacodigos abma";
		    $SQL.= " WHERE abma.flota_id =". $loginClassActual->tablaId;
		    if (!$mysqli->real_query($SQL)) {
      	 		$loginClassActual->errorCode = 2;
       			return  $loginClassActual;
     		}
     		$resultado = BykomClientePhone::getResultado($mysqli);
     		$loginClassActual->cantidadSubCuentas = $resultado->cantidad();
     		//Verificacion de acceso movil
     		$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     		if (mysqli_connect_errno()) {
     			$loginClassActual->errorCode = 1;
       			return  $loginClassActual;
     		}
     		$SQL = "SELECT tlma.ACCESS_PHONE as accessPhone From tlmapersonas tlma";
		    $SQL.= " WHERE tlma.ORDER_ID =". $loginClassActual->tablaId;
     		if (!$mysqli->real_query($SQL)) {
      	 		$loginClassActual->errorCode = 2;
       			return  $loginClassActual;
     		}
     		$resultado = BykomClientePhone::getResultado($mysqli);
     		$accessPhone = $resultado->campo('accessPhone',0);
		
		} else if ($loginClassActual->objetivo == 2){ // Movil
			$loginClassActual->objetivoDB = 2;
			$loginClassActual->cuentaFk	  = $loginClassActual->tablaId;
			$loginClassActual->cantidadSubCuentas = 1;
			//Verificacion de acceso movil
			$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     		if (mysqli_connect_errno()) {
     			$loginClassActual->errorCode = 1;
       			return  $loginClassActual;
     		}
			$SQL = "SELECT abma.codigocl as codigocl, abma.ACCESS_PHONE as accessPhone From abmacodigos abma";
		    $SQL.= " WHERE abma.order_id =". $loginClassActual->tablaId;
		    if (!$mysqli->real_query($SQL)) {
      	 		$loginClassActual->errorCode = 2;
       			return  $loginClassActual;
     		}
     		$resultado = BykomClientePhone::getResultado($mysqli);
     		$accessPhone = $resultado->campo('accessPhone', 0);
			
		} else if ($loginClassActual->objetivo == 5){ //Dealer
			$loginClassActual->objetivoDB = 5;
			$loginClassActual->cuentaFk	  = $loginClassActual->tablaId;
			//Busqueda de todas las flotas y moviles sin flota del Dealer
     		$resultado = BykomClientePhone::Cuentas_Cliente_Movil_Dealer($loginClassActual->tablaId);
     		$loginClassActual->cantidadSubCuentas = $resultado->cantidad();
     		//Verificacion de acceso movil
     		$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     		if (mysqli_connect_errno()) {
     			$loginClassActual->errorCode = 1;
       			return  $loginClassActual;
     		}
     		$SQL = "SELECT d.permisoMobile as accessPhone From dealer d";
		    $SQL.= " WHERE d.id =". $loginClassActual->tablaId;
     		if (!$mysqli->real_query($SQL)) {
      	 		$loginClassActual->errorCode = 2;
       			return  $loginClassActual;
     		}
     		$resultado = BykomClientePhone::getResultado($mysqli);
     		$accessPhone = $resultado->campo('accessPhone',0);			
		}
		if ($accessPhone == NULL || $accessPhone != 1) {
			//No tiene acceso a celular.
			$loginClassActual->errorCode = 150;
		}
     	return  $loginClassActual;
     }
     
     /**********************************************************************/
     function Cuentas_Cliente_Movil_Flota($flotaId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "SELECT abma.order_id as id, 
     					abma.nombre as nombre, 
     					abma.nombre_dos as nombreDos,
     					abma.avl_patente as patente";
     	$SQL .= " FROM abmacodigos abma";
        $SQL .= " WHERE abma.FLOTA_ID = " . $flotaId;
        $SQL .= " ORDER BY nombre";
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
	 
	 /**********************************************************************/
     function Cuentas_Cliente_Movil_Dealer($dealerId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "select if(isnull(ABMA.`FLOTA_ID`), ABMA.ORDER_ID, ABMA.`FLOTA_ID`) as id,
       					if(isnull(ABMA.`FLOTA_ID`), CONCAT('Movil: ',ABMA.`AVL_PATENTE`), CONCAT('Flota: ',TLMA.`NOMBRE`)) as NOMBRE,
       					if(isnull(ABMA.`FLOTA_ID`), 0, 1) as ES_FLOTA
				 from `dealer_cuenta` D_Cta
				 inner join abmacodigos as ABMA on ABMA.`ORDER_ID` = D_Cta.`cuentaFk` and D_Cta.objetivo=2
				 left join tlmapersonas as TLMA on TLMA.`ORDER_ID` = ABMA.`FLOTA_ID`
				 where D_Cta.`dealerFk` = ".$dealerId." and
      				   (isnull(D_Cta.`caduca`) or D_Cta.`caduca` >= now()) ";
		$SQL.= "UNION
				select distinct if(isnull(ABMA.`FLOTA_ID`), ABMA.ORDER_ID, ABMA.`FLOTA_ID`) as id,
							    if(isnull(ABMA.`FLOTA_ID`), CONCAT('Movil: ',ABMA.`AVL_PATENTE`), CONCAT('Flota: ',TLMA.`NOMBRE`)) as NOMBRE,
						        if(isnull(ABMA.`FLOTA_ID`), 0, 1) as ES_FLOTA
				from `dealer_rc` D_Rc
				inner join abmacodigos as ABMA on ABMA.`ID_RC` = D_Rc.`empresaFk` and D_Rc.objetivo=2
				left join tlmapersonas as TLMA on TLMA.`ORDER_ID` = ABMA.`FLOTA_ID`
				where D_Rc.`dealerFk` = ".$dealerId." and
				      (isnull(D_Rc.`caduca`) or D_Rc.`caduca` >= now()) ";
		$SQL.= "UNION
				select distinct if(isnull(ABMA.`FLOTA_ID`), ABMA.ORDER_ID, ABMA.`FLOTA_ID`) as id,
						        if(isnull(ABMA.`FLOTA_ID`), CONCAT('Movil: ',ABMA.`AVL_PATENTE`), CONCAT('Flota: ',TLMA.`NOMBRE`)) as NOMBRE,
						        if(isnull(ABMA.`FLOTA_ID`), 0, 1) as ES_FLOTA
				from `dealer_flota` D_Flota
				inner join abmacodigos as ABMA on ABMA.`FLOTA_ID` = D_Flota.`flotaFk`
				left join tlmapersonas as TLMA on TLMA.`ORDER_ID` = ABMA.`FLOTA_ID`
				where D_Flota.`dealerFk` = ".$dealerId." and
				      (isnull(D_Flota.`caduca`) or D_Flota.`caduca` >= now())
				ORDER BY id";
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
     /**********************************************************************/
/**********************************************************************************************************/
	function getCuentasByAlias($aliasId,$iObjetivo) //retorna todos los ID de los moviles que puede ver un Alias
	{
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB);
     	if (mysqli_connect_errno()) {
       		return new cResultado();
     	}
	  	$SQL = "SELECT id as iId, aliasId as iAliasId, movilId as iCuentaId, caduca as dCaduca, objetivo as iObjetivo
	  		 FROM alias_movil am WHERE am.aliasId = ". $aliasId;
	  	if($iObjetivo!=""){
	  		$SQL.= " and am.objetivo = $iObjetivo ";
	  	}
	  	if (!$mysqli->real_query($SQL)) {
      	 	return ("error de query");
     	}
     	return BykomClientePhone::getResultado($mysqli);
	}
	/**
	 * by Rodrigo A. Rio <rrio@aplay.com.ar>
	 *
	 */
	function getFlotasByAlias($aliasId) //retorna todos los ID de las flotas que puede ver un Alias
	{
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB);
     	if (mysqli_connect_errno()) {
       		return new cResultado();
     	}
	  	$SQL = "SELECT id as iId, aliasFk as iAliasId, flotaFk as iFlotaId, caduca as dCaduca
	  			 FROM alias_flota af WHERE af.aliasFk = ". $aliasId;

	  	if (!$mysqli->real_query($SQL)) {
      	 	return ("error de query");
     	}
     	return BykomClientePhone::getResultado($mysqli);
	}
	/**
	 * by Rodrigo A. Rio <rrio@aplay.com.ar>
	 *
	 */
	function getRCByAlias($aliasId,$iObjetivo) //retorna todos los ID de los RC que puede ver un Alias
	{
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB);
     	if (mysqli_connect_errno()) {
       		return new cResultado();
     	}
	  	$SQL = "SELECT id as iId, aliasFk as iAliasId, empresaFk as iEmpresaId, caduca as dCaduca, objetivo as iObjetivo
	  			FROM alias_rc arc WHERE arc.aliasFk = ". $aliasId ;
	  	if($iObjetivo != "" ){
	  		$SQL .= " and arc.objetivo = $iObjetivo ";
	  	}
	  	if (!$mysqli->real_query($SQL)) {
      	 	return ("error de query");
     	}
     	return BykomClientePhone::getResultado($mysqli);
	}
    /**
     *
     */
	function permisoAlias($idAlias,$permiso){
     	 global $LOGGER;
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	     }
	    $vPermisos = array(
	    			"permisoMonitor","permisoComandosGPRS","permisoComandoSMS","permisoVerReportes",
	    			"permisoVerPuntos","permisoVerZonas","permisoVerContactos","permisoVerLogistica",
	    			"permisoModificarPuntos","permisoModificarZonas","permisoModificarContactos","permisoModificarLogistica",
	    			"permisoMobile","permisoAccedeSetup","permisoAccedeEventos","permisoAccedeUsuarios",
	    			"permisoAccedeFacturas","permisoAccedeZonas","permisoAccedeContactos","permisoAccedeHorarios",
	    			"habilitarFijo","habilitarMovil","habilitarFlota","habilitarRC","habilitarRCFijo"
	    			);
   		$SQL=" Select $vPermisos[$permiso] from aliases where id=$idAlias";
   		if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	$result = BykomClientePhone::getResultado($mysqli);
     	if($result->cantidad()>0){
     		$value = $result->campo("$vPermisos[$permiso]",0);		
     	}else{
     		$value = 0;
     	}
     	return $value;
	     
     }
	/**
     * Obtiene los moviles de un alias.
     * @param int $id
     * @param int $iDealerId
     * @param string $orderBy
     * @return cResultado
     * <rrio@aplay.com.ar>
     */
	function Cuentas_Cliente_Movil_DealerAlias($id,$iDealerId, $orderBy="id"){
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	     }
   		$SQL="";
   		$SQLSELECT = " SELECT ABMA.`ORDER_ID` as id,
   					abma.nombre as nombre,
		     		abma.nombre_dos as nombreDos,
		     		abma.codigocl as codigocl,
		     		abma.AVL_PATENTE as patente ";
     	$SQLFROM1="";
	 	if( BykomClientePhone::permisoAlias($id,21)){//si tiene habilitado movil (habilitarMovil=1)
			$SQLFROM1 = " from `alias_movil` A_Cta
			   inner join abmacodigos as ABMA on ABMA.`ORDER_ID` = A_Cta.`movilId` and A_Cta.objetivo = 2
			   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			   where A_Cta.`aliasId` = ".$id." and  (isnull(A_Cta.`caduca`) or A_Cta.`caduca` >= now())  ";
			$resultRows = BykomClientePhone::getCuentasByAlias($id,2);
			if($resultRows->cantidad()==0){//si no tiene asignada ninguna cuenta se le asigna las del dealer
				  $SQLFROM1 = " from `dealer_cuenta` D_Cta
				   inner join abmacodigos as ABMA on ABMA.`ORDER_ID` = D_Cta.`cuentaFk` and D_Cta.objetivo = 2
				   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
				   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
				   where D_Cta.`dealerFk` = ".$iDealerId." and (isnull(D_Cta.`caduca`) or D_Cta.`caduca` >= now())
				   and D_Cta.objetivo = 2 ";
			}
			$SQL.= $SQLSELECT;
			$SQL.= $SQLFROM1;
	    }


		$SQLFROM2 = "";
		if( BykomClientePhone::permisoAlias($id,23)){//si tiene habilitado Empresas (habilitarRC=1)
			if($SQL!=""){
				$SQL.= " UNION ";
			}
			$SQLFROM2 = " from `alias_rc` A_Rc
				   inner join abmacodigos as ABMA on ABMA.`ID_RC` = A_Rc.`empresaFk` and A_Rc.objetivo = 2
				   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
				   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
				   where A_Rc.`aliasFk` = ".$id." and  (isnull(A_Rc.`caduca`) or A_Rc.`caduca` >= now())
				   and ABMA.OBJETIVO = 2   ";
			$resultRows =  BykomClientePhone::getRCByAlias($id,2);
			if($resultRows->cantidad()==0){//si no tiene asignada ninguna empresa se le asigna las del dealer
				  $SQLFROM2 = " from `dealer_rc` D_Rc
				   inner join abmacodigos as ABMA on ABMA.`ID_RC` = D_Rc.`empresaFk` and D_Rc.objetivo = 2
				   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
				   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
				   where D_Rc.`dealerFk` = ".$iDealerId." and  (isnull(D_Rc.`caduca`) or D_Rc.`caduca` >= now())
					and ABMA.OBJETIVO = 2 ";
			}
			$SQL.= $SQLSELECT;
			$SQL.= $SQLFROM2;
		}
		if( BykomClientePhone::permisoAlias($id,22)){//si tiene habilitado Flota (habilitarFlota=1)
			if($SQL!=""){
				$SQL.= " UNION ";
			}
			$SQLFROM3 =" from `alias_flota` A_Flota
				   inner join abmacodigos as ABMA on ABMA.`FLOTA_ID` = A_Flota.`flotaFk`
				   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
				   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
				   where A_Flota.`aliasFk` = ".$id." and (isnull(A_Flota.`caduca`) or A_Flota.`caduca` >= now())
				   and ABMA.OBJETIVO = 2";
			$resultRows =  BykomClientePhone::getFlotasByAlias($id);
			if($resultRows->cantidad()==0){
				  $SQLFROM3 = " from `dealer_flota` D_Flota
				   inner join abmacodigos as ABMA on ABMA.`FLOTA_ID` = D_Flota.`flotaFk`
				   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
				   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
				   where D_Flota.`dealerFk` = ".$iDealerId." and (isnull(D_Flota.`caduca`) or D_Flota.`caduca` >= now())
				   and ABMA.OBJETIVO = 2";
			}
			$SQL.= $SQLSELECT;
			$SQL.= $SQLFROM3;
		}
		if($SQL!=""){
			$SQL	.= " ORDER BY " . $orderBy;
		}
	 	if($SQL==""){
	 	 	//return new cResultado();
	 	 	return "";
	 	}
     	if (!$mysqli->real_query($SQL)){
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
    }     

    /**********************************************************************/
     function Cuentas_Cliente_Fijo($fijoId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL = "SELECT abma.codigocl as codigocl From abmacodigos abma";
		$SQL.= " WHERE abma.order_id =". $fijoId;
		if (!$mysqli->real_query($SQL)) {
      		$loginClassActual->errorCode = 2;
       		return  $loginClassActual;
     	}
     	$resultado = BykomClientePhone::getResultado($mysqli);
     	$codigocl = $resultado->campo('codigocl',0);
     	
		$SQL = "SELECT abma.order_id as id, abma.nombre as nombre, abma.nombre_dos as nombreDos";
		$SQL.= " FROM abmacodigos abma";
		$SQL.= " WHERE abma.codigocl = ". $codigocl . " AND abma.objetivo = 1 UNION(";
     	$SQL .= "SELECT abma.order_id as id, abma.nombre as nombre, abma.nombre_dos as nombreDos";
     	$SQL.= " FROM abrlsubcuentas abrl";
     	$SQL.= " INNER JOIN abmacodigos abma ON abma.codigocl = abrl.codigocl";
		$SQL.= " WHERE abrl.codigo_id = ". $codigocl . " AND abma.objetivo = 1 AND abma.ACCESS_PHONE = 1)";
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
    /**********************************************************************/
    function Info_Alias_Phone($tablaId, $objetivo)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "SELECT * FROM aliasesphone ap";
        $SQL .= " WHERE ap.tablaId = " . $tablaId . " AND ap.objetivo=" . $objetivo;
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
     /**********************************************************************/
    function Info_Posicion_Movil($movilId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "SELECT * FROM posi_actual pa";
        $SQL .= " WHERE pa.ORDER_RL = " . $movilId;
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
     /**********************************************************************/
     function Info_Movil($movilId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "SELECT abma.order_id as id, 
     					abma.nombre as nombre, 
     					abma.nombre_dos as nombreDos,
     					abma.avl_patente as patente";
     	$SQL .= " FROM abmacodigos abma";
        $SQL .= " WHERE abma.ORDER_ID = " . $movilId;
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
     /**********************************************************************/
     function Info_Fijo($fijoId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "SELECT abma.nombre as nombre, abma.nombre_dos as nombreDos From abmacodigos abma WHERE abma.order_id = " . $fijoId;
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
     /**********************************************************************/
     function Info_Flota($flotaId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "SELECT tlma.nombre as nombre, tlma.nombre_dos as nombreDos From tlmapersonas tlma WHERE tlma.order_id = " . $flotaId;
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
	 /**********************************************************************/
     function Info_Dealer($dealerId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "SELECT concat(d.nombre,' ',d.apellido) as nombre From dealer d WHERE d.id = " . $dealerId;
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
	 /**********************************************************************/
     function Info_Alias($aliasId){
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "SELECT a.nombre as nombre From aliases a WHERE a.id = " . $aliasId;
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
     /**********************************************************************/
     function Info_Fijo_Estado($fijoId)
	 {
	 	$mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     	if (mysqli_connect_errno()) {
       		printf("Conexion fallida: %s\n", mysqli_connect_error());
       		exit();
     	}
     	$SQL  = "call z_consulta_InfoCuenta('$fijoId')"; 
     	if (!$mysqli->real_query($SQL)) {
       		printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
     }
    
	/**********************************************************************/
	function Consulta_Evento($cuenta,$fechai,$fechaf,$limitacion,$tipo,$iniPaginacion,$contar)
    {                             
     $mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
     $SQL = "call z_consulta_evento_bis('$cuenta','$fechai','$fechaf','$limitacion','$tipo',".RESULTADO_EVENTOS.",0,'$contar')";
     if (!$mysqli->real_query($SQL))
     {
      printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
      exit();
     }
     return BykomClientePhone::getResultado($mysqli);
    }
	/**********************************************************************/
	function Obtener_Direccion_Abreviada($direccion)
    {
    	if (strpos($direccion,"|") === false || strpos($direccion,"Error") !== false) return $direccion;
    	
    	$callePrincipal = substr($direccion, 0 , strpos($direccion,"|"));
        
        $direccion = substr($direccion, strpos($direccion,"|")+1);
        
        $calleTipo = substr($direccion,0,strpos($direccion,"|"));
        
        $direccion = substr($direccion, strpos($direccion,"|")+1);
        
        $alturaPrincipal = substr($direccion,0,strpos($direccion,"|"));
        
        $direccion = substr($direccion, strpos($direccion,"|")+1);
        
        $localidad = substr($direccion,0,strpos($direccion,"|"));
        
        $direccion = substr($direccion, strpos($direccion,"|")+1);
        
        $ciudad = $direccion;
        
        $alturaFormateada = "";
        
        if (trim($alturaPrincipal) == "-1")
        {
        	$alturaFormateada = "(Sin altura)";
        } else {
        	$alturaFormateada = "N&ordm; ".$alturaPrincipal;
        }
        $result = $callePrincipal." ".$alturaFormateada. " - ".$localidad." - ".$ciudad;
        
        return $result;
        
    	
    }
    /**********************************************************************/
    function Obtener_Palabra_Sentido($sentido)
    {
    	
    	$result = "";
    	if ($sentido >= 22 && $sentido <= 67)
    	{
    		$result = "NORESTE";
    	}
        if ($sentido >= 68 && $sentido <= 112)
    	{
    		$result = "ESTE";
    	}
    	if ($sentido >= 113 && $sentido <= 157)
    	{
    		$result = "SURESTE";
    	}
    	if ($sentido >= 157 && $sentido <= 202)
    	{
    		$result = "SUR";
    	}
    	if ($sentido >=203  && $sentido <= 247)
    	{
    		$result = "SUROESTE";
    	}
    	if ($sentido >= 248 && $sentido <= 292)
    	{
    		$result = "OESTE";
    	}
    	if ($sentido >= 293 && $sentido <= 337)
    	{
    		$result = "NOROESTE";
    	}
    	if (($sentido >= 338 && $sentido <= 360) || (($sentido >= 0 && $sentido <= 21)))
    	{
    		$result = "NORTE";
    	}
    	   
		return $result;
    }
    
    /**********************************************************************/
    function quitCero($string)
   	// Quita el primer cero de un string Coodenada si es que existe
	{
		$pos = 0;
		$charCero = substr($string, 0 , 1);
		$menos = "";

		if ($charCero == '-')
		{
			$menos = "-";
			$charCero = substr($string, 1 , 1);
			$pos += 1;
		}
	
		if ($charCero == '0')
		{
			$pos +=1;   
		}
		$result = $menos.substr($string,$pos);
		$result2 = str_replace(",", ".", $result);
		return $result2;
	
	}
	
	/**********************************************************************/
	function checkAccessPhoneService() {
		//REALIZO CONSULTA INICIAL AL SERVER
		$privateKeyCode = '1@%(&0A';
		$publicKeyCode = PUBLICKEYCODE;
		$resultado = BykomClientePhone::LoginDataActivation($privateKeyCode.$publicKeyCode);
		
		if (($resultado->cantidad() == 0)||(!$resultado->campo('data', 0))){
			return 0;
		}
		$data = str_replace("|",",",$resultado->campo('data', 0));
		$dataArray = split(",",$data);
		$MO = substr($dataArray[6],3); //
		if ($MO == NULL || $MO != 1 ) {
			return 0;
		}
		return 1;
	}
	/**********************************************************************/
	function LoginDataActivation($keyCode)
	{
    $mysqli = new mysqli(HOST, USER, PASSWORD, DB); 
	$SQL = "SELECT AES_DECRYPT(a.dato, '$keyCode') as data FROM `activacion` a limit 1";
	if (!$mysqli->real_query($SQL))
    {
      printf("Query Invalido: %s\nWhole query: %s\n", $mysqli->error, $SQL);
      exit();
    }
     return BykomClientePhone::getResultado($mysqli);
	}
	
    /**********************************************************************/
    function Cuentas_Cliente_Movil_BIS($order_id)
	{
	 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
     if (mysqli_connect_errno())
     {
       printf("Conexion fallida: %s\n", mysqli_connect_error());
       exit();
     }
	 $SQL = "SELECT ABMA.ORDER_ID as id,
		     		ABMA.`ID_CL` as Movil,
					ABMA.nombre as nombre,
        			ABMA.nombre_dos as nombreDos,
        			ABMA.codigocl,
			        RTRIM(CONCAT(ABMA.`NOMBRE`, ' ', ABMA.`NOMBRE_DOS`)) as Descripcion,
		       		RTRIM(ABMA.`AVL_IDENTIFICADOR`) as Identificador,
	         		RTRIM(ABMA.`AVL_MARCA`) as Marca,
      		 		RTRIM(ABMA.`AVL_MODELO`) as Modelo,
		     		RTRIM(ABMA.`AVL_PATENTE`) as Patente,
       		 		RTRIM(ABMA.`AVL_ANIO`) as Anio,
       				RTRIM(ABMA.`AVL_COLOR`) as Color,
			        TipoAvl.`ORDER_ID` as CodeAvl,
       				RTRIM(TipoAvl.`IMAGEN`) as TipoAvl,
			        RTRIM(TipoAvl.`NOMBRE`) as TipoAvlNombre,
       				0 as Grupo,
       				ABMA.`ACTIVO` as Activo,
			        ABMA.`AVL_RESTRINGIDO` as AvlRestringido,
					concat(CRC.`CODIGOALFA`,'-',ABMA.`ID_CL`,'-',cast(ABMA.particion as char)) as Codigo,
        			CRC.`IMAGEN` as Imagen,
        			CRC.`CODIGOALFA` as CodigoAlfa
			 from `abmacodigos` ABMA
			 LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			 inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			 where ABMA.ORDER_ID = ".$order_id." and ABMA.ACCESS_PHONE = 1" ;

     if (!$mysqli->real_query($SQL))    {
       exit();
     }
     return BykomClientePhone::getResultado($mysqli);
    }
    
	/**********************************************************************/
    function Cuentas_Cliente_Movil_FlotaAlias($aliasId, $orderBy = 'id')
	{
	 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
     if (mysqli_connect_errno())
     {
       printf("Conexion fallida: %s\n", mysqli_connect_error());
       exit();
     }
	  $SQL = "SELECT ABMA.ORDER_ID as id,
	 		        ABMA.nombre as nombre,
			        ABMA.nombre_dos as nombreDos,
			       	ABMA.codigocl,
	   				ABMA.`ID_CL` as Movil,
	   				RTRIM(CONCAT(ABMA.`NOMBRE`, ' ', ABMA.`NOMBRE_DOS`)) as Descripcion,
       				RTRIM(ABMA.`AVL_IDENTIFICADOR`) as Identificador,
       				RTRIM(ABMA.`AVL_MARCA`) as Marca,
       				RTRIM(ABMA.`AVL_MODELO`) as Modelo,
       				RTRIM(ABMA.`AVL_PATENTE`) as patente,
       				RTRIM(ABMA.`AVL_ANIO`) as Anio,
       				RTRIM(ABMA.`AVL_COLOR`) as Color,
       				TipoAvl.`ORDER_ID` as CodeAvl,
       				RTRIM(TipoAvl.`IMAGEN`) as TipoAvl,
       				RTRIM(TipoAvl.`NOMBRE`) as TipoAvlNombre,
       				if(isnull(ABMA.`GRUPOMOVIL`), 0, ABMA.`GRUPOMOVIL`) as Grupo,
       				ABMA.`ACTIVO` as Activo,
       				ABMA.`AVL_RESTRINGIDO` as AvlRestringido,
       				concat(CRC.`CODIGOALFA`,'-',ABMA.`ID_CL`,'-',cast(ABMA.particion as char)) as Codigo,
       				CRC.`IMAGEN` as Imagen,
       				CRC.`CODIGOALFA` as CodigoAlfa
			 from `abmacodigos` ABMA
			 inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			 LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			 where ABMA.`ORDER_ID` IN (select AM.`movilId` from `alias_movil` AM where AM.aliasId = ".$aliasId.")
	  		 ORDER BY " . $orderBy;

     if (!$mysqli->real_query($SQL))
     {
       exit();
     }
     return BykomClientePhone::getResultado($mysqli);
    }
    
	/**********************************************************************/
	function Cuentas_ClienteFijoAlias($aliasId){
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno()) {
	       exit();
	     }
	     $SQL = "SELECT abma.order_id as id,
	     				abma.nombre as nombre,
	     				abma.nombre_dos as nombreDos,
	     				abma.codigocl as codigocl,
	     				abma.AVL_PATENTE as patente,
	     				abma.AVL_IDENTIFICADOR as identificador,
	     				concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
	     				CRC.IMAGEN as Imagen,
	        			CRC.CODIGOALFA as CodigoAlfa
	        			 from `alias_movil` am
				 inner join abmacodigos as abma on abma.`ORDER_ID` = am.`movilId` and am.objetivo = 1
	             inner JOIN rcmacodigos as CRC on CRC.ORDER_ID = abma.id_rc
	             WHERE am.`aliasId`  = " . $aliasId. "  and abma.ACCESS_PHONE = 1
	              UNION (
	   			 SELECT abma.order_id as id,
	     				abma.nombre as nombre,
	     				abma.nombre_dos as nombreDos,
	     				abma.codigocl as codigocl,
	     				abma.AVL_PATENTE as patente,
	     				abma.AVL_IDENTIFICADOR as identificador,
	     				concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
	     				CRC.IMAGEN as Imagen,
	        			CRC.CODIGOALFA as CodigoAlfa
	             FROM abrlsubcuentas abrl
	     		 INNER JOIN abmacodigos abma ON abma.codigocl = abrl.codigocl
	      		 inner join alias_movil  am on abma.`ORDER_ID` = am.`movilId` and am.objetivo = 1 
				 INNER JOIN rcmacodigos as CRC on CRC.ORDER_ID = abma.id_rc
		 	 	WHERE am.`aliasId` = ". $aliasId . " AND abma.objetivo = 1  and  abma.ACCESS_PHONE = 1) ";
	
		 if (!$mysqli->real_query($SQL)) {
	        exit();
	     }
	     return BykomClientePhone::getResultado($mysqli);
    }
    
 	/**
     * Obtiene las flotas de un dealer
     * @param int $idDealer
     * @param string $orderBy
     * @return cResultado
     * <rrio@aplay.com.ar>
     */
    function Cuentas_Cliente_Flotas_Dealer($idDealer,$orderBy,$idRC){
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	     }
    	 $SQL= "select RTRIM(tlma.NOMBRE_MIX) as sDescription, df.flotaFk as iFlotaId, df.*,abma.ID_RC as idRc
				 from `dealer_flota` df
				 inner join tlmapersonas as tlma on tlma.ORDER_ID = df.flotaFk
				 join abmacodigos abma on abma.FLOTA_ID  = df.flotaFk
			     where df.`dealerFk` = ".$idDealer." and (isnull(df.`caduca`) or df.`caduca` >= now())";
    	 if($idRC != null){
    	 	$SQL.= " and abma.ID_RC = $idRC ";
    	 }
    	 $SQL.= " group by sDescription ";

    	if($orderBy != ""){
			$SQL.= " ORDER BY " . $orderBy;
    	}
    	if (!$mysqli->real_query($SQL)){
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
    }
    /**
     * Obtiene los RC de un dealer segun el tipo (fijo o movil)
     * @param int $idDealer
     * @param string $orderBy
     * @param int $iObjetivo
     * @return cResultado
     * <rrio@aplay.com.ar>
     */
    function Cuentas_Cliente_Rc_Dealer($idDealer,$orderBy,$iObjCuenta){
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	     }
    	 $SQL= "SELECT RTRIM(rc.NOMBRE) as sDescription, drc.empresaFk as iRCId, drc.objetivo as iObjetivo
				from `dealer_rc` drc
				inner join rcmacodigos as rc on rc.ORDER_ID = drc.empresaFk
			    where drc.`dealerFk` = ".$idDealer." and (isnull(drc.`caduca`) or drc.`caduca` >= now())
			    and drc.objetivo = $iObjCuenta ";

    	if($orderBy != ""){
			$SQL.= " ORDER BY " . $orderBy;
    	}
    	if (!$mysqli->real_query($SQL)){
       		exit();
     	}
     	return BykomClientePhone::getResultado($mysqli);
    }
    
/**
	 * Obtengo las cuentas de tipo fijo para un dealer
	 * @param int $iDealerId
	 * @param string $orderBy
	 * @param int $iRc
	 */
    function getCuentasByDealer($iDealerId,$orderBy,$iRc){
		$mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	    if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	    }
	    $SQL = "";
	    if($iRc==""){
			$SQL.= "SELECT abma.order_id as ORDER_ID,
     				abma.nombre as nombre,
     				abma.nombre_dos as nombre_dos,
     				abma.codigocl as codigocl,
     				abma.AVL_PATENTE as patente,
     				abma.AVL_IDENTIFICADOR as identificador,
     				concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
     				CRC.IMAGEN as Imagen,
        			CRC.CODIGOALFA as CodigoAlfa,
        			abma.LATITUD as latitud,
        			abma.LONGITUD as longitud,
        			abma.ACTIVO as activo
			   from `dealer_cuenta` D_Cta
			   inner join abmacodigos as ABMA on ABMA.`ORDER_ID` = D_Cta.`cuentaFk` and D_Cta.objetivo = 1
			   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			   where D_Cta.`dealerFk` = ".$iDealerId." and (isnull(D_Cta.`caduca`) or D_Cta.`caduca` >= now())
			   and D_Cta.objetivo = 1 ";
			$SQL.= " UNION ";
	    }
		$SQL.= "SELECT abma.order_id as ORDER_ID,
		     		abma.nombre as nombre,
		     		abma.nombre_dos as nombre_dos,
		     		abma.codigocl as codigocl,
		     		abma.AVL_PATENTE as patente,
		     		abma.AVL_IDENTIFICADOR as identificador,
		     		concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
		     		CRC.IMAGEN as Imagen,
		        	CRC.CODIGOALFA as CodigoAlfa,
		        	abma.LATITUD as latitud,
        			abma.LONGITUD as longitud,
        			abma.ACTIVO as activo
			   from `dealer_rc` D_Rc
			   inner join abmacodigos as ABMA on ABMA.`ID_RC` = D_Rc.`empresaFk` and D_Rc.objetivo = 1 ";
			   if($iRc!=""){
			   		$SQL.= " and D_Rc.empresaFk = $iRc ";
			   }
		$SQL.= " inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			    LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			    where D_Rc.`dealerFk` = ".$iDealerId." and  (isnull(D_Rc.`caduca`) or D_Rc.`caduca` >= now())
				and ABMA.OBJETIVO = 1 ";
		if(trim($orderBy)){
			$SQL.= " ORDER BY " . $orderBy;
		}
	 	if (!$mysqli->real_query($SQL)){
	       exit();
	    }
	    return BykomClientePhone::getResultado($mysqli);
    }
    
	 function Cuentas_Cliente_Movil_Dealer2($id, $orderBy="id"){
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	     }
		$SQL= "SELECT ABMA.ORDER_ID as id,
		  	   ABMA.`NOMBRE` as nombre,
			   ABMA.`NOMBRE_DOS` as nombreDos,
			   ABMA.`ID_CL` as Movil,
			   RTRIM(CONCAT(ABMA.`NOMBRE`, ' ', ABMA.`NOMBRE_DOS`)) as Descripcion,
               RTRIM(ABMA.`AVL_IDENTIFICADOR`) as Identificador,
               RTRIM(ABMA.`AVL_MARCA`) as Marca,
               RTRIM(ABMA.`AVL_MODELO`) as Modelo,
               RTRIM(ABMA.`AVL_PATENTE`) as patente,
               RTRIM(ABMA.`AVL_ANIO`) as Anio,
               RTRIM(ABMA.`AVL_COLOR`) as Color,
               TipoAvl.`ORDER_ID` as CodeAvl,
               RTRIM(TipoAvl.`IMAGEN`) as TipoAvl,
               RTRIM(TipoAvl.`NOMBRE`) as TipoAvlNombre,
               if(isnull(ABMA.`FLOTA_ID`), 0, ABMA.`FLOTA_ID`) as Grupo,
               ABMA.`ACTIVO` as Activo,
               ABMA.`AVL_RESTRINGIDO` as AvlRestringido
			   from `dealer_cuenta` D_Cta
			   inner join abmacodigos as ABMA on ABMA.`ORDER_ID` = D_Cta.`cuentaFk` and D_Cta.objetivo = 2
			   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			   where D_Cta.`dealerFk` = ".$id." and (isnull(D_Cta.`caduca`) or D_Cta.`caduca` >= now())
			   and D_Cta.objetivo = 2 ";
		$SQL.= " UNION ";
		$SQL.= "SELECT ABMA.ORDER_ID as id,
		  	   ABMA.`NOMBRE` as nombre,
			   ABMA.`NOMBRE_DOS` as nombreDos,
			   ABMA.`ID_CL` as Movil,
			   RTRIM(CONCAT(ABMA.`NOMBRE`, ' ', ABMA.`NOMBRE_DOS`)) as Descripcion,
               RTRIM(ABMA.`AVL_IDENTIFICADOR`) as Identificador,
               RTRIM(ABMA.`AVL_MARCA`) as Marca,
               RTRIM(ABMA.`AVL_MODELO`) as Modelo,
               RTRIM(ABMA.`AVL_PATENTE`) as patente,
               RTRIM(ABMA.`AVL_ANIO`) as Anio,
               RTRIM(ABMA.`AVL_COLOR`) as Color,
               TipoAvl.`ORDER_ID` as CodeAvl,
               RTRIM(TipoAvl.`IMAGEN`) as TipoAvl,
               RTRIM(TipoAvl.`NOMBRE`) as TipoAvlNombre,
               if(isnull(ABMA.`FLOTA_ID`), 0, ABMA.`FLOTA_ID`) as Grupo,
               ABMA.`ACTIVO` as Activo,
               ABMA.`AVL_RESTRINGIDO` as AvlRestringido
			   from `dealer_rc` D_Rc
			   inner join abmacodigos as ABMA on ABMA.`ID_RC` = D_Rc.`empresaFk` and D_Rc.objetivo = 2
			   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			   where D_Rc.`dealerFk` = ".$id." and  (isnull(D_Rc.`caduca`) or D_Rc.`caduca` >= now())
				and ABMA.OBJETIVO = 2 ";

		$SQL.= " UNION ";
		$SQL.= "SELECT ABMA.ORDER_ID as id,
		  	   ABMA.`NOMBRE` as nombre,
			   ABMA.`NOMBRE_DOS` as nombreDos,
			   ABMA.`ID_CL` as Movil,
			   RTRIM(CONCAT(ABMA.`NOMBRE`, ' ', ABMA.`NOMBRE_DOS`)) as Descripcion,
               RTRIM(ABMA.`AVL_IDENTIFICADOR`) as Identificador,
               RTRIM(ABMA.`AVL_MARCA`) as Marca,
               RTRIM(ABMA.`AVL_MODELO`) as Modelo,
               RTRIM(ABMA.`AVL_PATENTE`) as patente,
               RTRIM(ABMA.`AVL_ANIO`) as Anio,
               RTRIM(ABMA.`AVL_COLOR`) as Color,
               TipoAvl.`ORDER_ID` as CodeAvl,
               RTRIM(TipoAvl.`IMAGEN`) as TipoAvl,
               RTRIM(TipoAvl.`NOMBRE`) as TipoAvlNombre,
               if(isnull(ABMA.`FLOTA_ID`), 0, ABMA.`FLOTA_ID`) as Grupo,
               ABMA.`ACTIVO` as Activo,
               ABMA.`AVL_RESTRINGIDO` as AvlRestringido
			   from `dealer_flota` D_Flota
			   inner join abmacodigos as ABMA on ABMA.`FLOTA_ID` = D_Flota.`flotaFk`
			   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			   where D_Flota.`dealerFk` = ".$id." and (isnull(D_Flota.`caduca`) or D_Flota.`caduca` >= now())
			   and ABMA.OBJETIVO = 2  ";
		
		$SQL.= " ORDER BY " . $orderBy;

	     if (!$mysqli->real_query($SQL)) {
	       exit();
	     }
	     return BykomClientePhone::getResultado($mysqli);
    }
    
	function Cuentas_Cliente_MovilByFlotas_Dealer($id, $orderBy="Id"){
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno()) {
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	     }
		 $SQL.= "SELECT ABMA.ORDER_ID as id,
			   ABMA.`ID_CL` as Movil,
			    ABMA.`NOMBRE` as nombre,
			   ABMA.`NOMBRE_DOS` as nombreDos,
			   RTRIM(CONCAT(ABMA.`NOMBRE`, ' ', ABMA.`NOMBRE_DOS`)) as Descripcion,
               RTRIM(ABMA.`AVL_IDENTIFICADOR`) as Identificador,
               RTRIM(ABMA.`AVL_MARCA`) as Marca,
               RTRIM(ABMA.`AVL_MODELO`) as Modelo,
               RTRIM(ABMA.`AVL_PATENTE`) as patente,
               RTRIM(ABMA.`AVL_ANIO`) as Anio,
               RTRIM(ABMA.`AVL_COLOR`) as Color,
               TipoAvl.`ORDER_ID` as CodeAvl,
               RTRIM(TipoAvl.`IMAGEN`) as TipoAvl,
               RTRIM(TipoAvl.`NOMBRE`) as TipoAvlNombre,
               if(isnull(ABMA.`FLOTA_ID`), 0, ABMA.`FLOTA_ID`) as Grupo,
               ABMA.`ACTIVO` as Activo,
               ABMA.`AVL_RESTRINGIDO` as AvlRestringido
			   from `dealer_flota` D_Flota
			   inner join abmacodigos as ABMA on ABMA.`FLOTA_ID` = D_Flota.`flotaFk`
			   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			   where D_Flota.`dealerFk` = ".$id." and (isnull(D_Flota.`caduca`) or D_Flota.`caduca` >= now())
			   and ABMA.OBJETIVO = 2  ";
		 $SQL.= " ORDER BY " . $orderBy;

	     if (!$mysqli->real_query($SQL)){
	       exit();
	     }
	     return BykomClientePhone::getResultado($mysqli);
    }
 
	function Cuentas_Cliente_MovilByRc_Dealer($id, $orderBy="id"){
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno())     {
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	     }
	
		 $SQL.= "SELECT ABMA.ORDER_ID as id,
			   ABMA.`ID_CL` as Movil,
			    ABMA.`NOMBRE` as nombre,
			   ABMA.`NOMBRE_DOS` as nombreDos,
			   RTRIM(CONCAT(ABMA.`NOMBRE`, ' ', ABMA.`NOMBRE_DOS`)) as Descripcion,
               RTRIM(ABMA.`AVL_IDENTIFICADOR`) as Identificador,
               RTRIM(ABMA.`AVL_MARCA`) as Marca,
               RTRIM(ABMA.`AVL_MODELO`) as Modelo,
               RTRIM(ABMA.`AVL_PATENTE`) as patente,
               RTRIM(ABMA.`AVL_ANIO`) as Anio,
               RTRIM(ABMA.`AVL_COLOR`) as Color,
               TipoAvl.`ORDER_ID` as CodeAvl,
               RTRIM(TipoAvl.`IMAGEN`) as TipoAvl,
               RTRIM(TipoAvl.`NOMBRE`) as TipoAvlNombre,
               if(isnull(ABMA.`FLOTA_ID`), 0, ABMA.`FLOTA_ID`) as Grupo,
               ABMA.`ACTIVO` as Activo,
               ABMA.`AVL_RESTRINGIDO` as AvlRestringido
			   from `dealer_rc` D_Rc
			   inner join abmacodigos as ABMA on ABMA.`ID_RC` = D_Rc.`empresaFk` and D_Rc.objetivo = 2
			   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			   where D_Rc.`dealerFk` = ".$id." and  (isnull(D_Rc.`caduca`) or D_Rc.`caduca` >= now())
				and ABMA.OBJETIVO = 2 ";
	
		 $SQL.= " ORDER BY " . $orderBy;

	     if (!$mysqli->real_query($SQL))    {
	       exit();
	     }
	     return BykomClientePhone::getResultado($mysqli);
    }
	function Cuentas_ClienteAlias($aliasId){
		 global $LOGGER;
		 $mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	     if (mysqli_connect_errno()) {
		   $LOGGER->addLine('ERROR', mysqli_connect_error());
	       exit();
	     }
	
	     $SQL = "SELECT abma.order_id as ORDER_ID,
	     				abma.nombre as nombre,
	     				abma.nombre_dos as nombre_dos,
	     				abma.codigocl as codigocl,
	     				abma.AVL_PATENTE as patente,
	     				abma.AVL_IDENTIFICADOR as identificador,
	     				concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
	     				CRC.IMAGEN as Imagen,
	        			CRC.CODIGOALFA as CodigoAlfa
	        			 from `alias_movil` am
				 inner join abmacodigos as abma on abma.`ORDER_ID` = am.`movilId` and am.objetivo = 1
	             inner JOIN rcmacodigos as CRC on CRC.ORDER_ID = abma.id_rc
	             WHERE am.`aliasId`  = " . $aliasId. " and (isnull(am.`caduca`) or am.`caduca` >= now())
	              UNION (
	   			 SELECT abma.order_id as ORDER_ID,
	     				abma.nombre as nombre,
	     				abma.nombre_dos as nombre_dos,
	     				abma.codigocl as codigocl,
	     				abma.AVL_PATENTE as patente,
	     				abma.AVL_IDENTIFICADOR as identificador,
	     				concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
	     				CRC.IMAGEN as Imagen,
	        			CRC.CODIGOALFA as CodigoAlfa
	             FROM abrlsubcuentas abrl
	     		 INNER JOIN abmacodigos abma ON abma.codigocl = abrl.codigocl
	      		 inner join alias_movil  am on abma.`ORDER_ID` = am.`movilId` and am.objetivo = 1 and (isnull(am.`caduca`) or am.`caduca` >= now())
				 INNER JOIN rcmacodigos as CRC on CRC.ORDER_ID = abma.id_rc
		 	 	WHERE am.`aliasId` = ". $aliasId . " AND abma.objetivo = 1) ";
	
	
		 if (!$mysqli->real_query($SQL)) {
		 	$LOGGER->addLine('ERROR', $mysqli->error.' CONSULTA: '.$SQL);
	        exit();
	     }
	     return BykomClientePhone::getResultado($mysqli);
    }
	/**
	 * Obtengo las cuentas de tipo fijo para un dealer
	 * @param int $iDealerId
	 * @param string $orderBy
	 */
    function getFijosByDealer($iDealerId,$iRc,$orderBy="id"){
		$mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	    if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	    }
	    if($iRc==""){
				$SQL.= "SELECT abma.order_id as id,
	     				abma.nombre as nombre,
	     				abma.nombre_dos as nombreDos,
	     				abma.codigocl as codigocl,
	     				abma.AVL_PATENTE as patente,
	     				abma.AVL_IDENTIFICADOR as identificador,
	     				concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
	     				CRC.IMAGEN as Imagen,
	        			CRC.CODIGOALFA as CodigoAlfa,
	        			abma.LATITUD as latitud,
	        			abma.LONGITUD as longitud,
	        			abma.ACTIVO as activo
				   from `dealer_cuenta` D_Cta
				   inner join abmacodigos as ABMA on ABMA.`ORDER_ID` = D_Cta.`cuentaFk` and D_Cta.objetivo = 1
				   inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
				   LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
				   where D_Cta.`dealerFk` = ".$iDealerId." and (isnull(D_Cta.`caduca`) or D_Cta.`caduca` >= now())
				   and D_Cta.objetivo = 1 ";
				$SQL.= " UNION ";
		 }
		$SQL.= "SELECT abma.order_id as id,
		     		abma.nombre as nombre,
		     		abma.nombre_dos as nombreDos,
		     		abma.codigocl as codigocl,
		     		abma.AVL_PATENTE as patente,
		     		abma.AVL_IDENTIFICADOR as identificador,
		     		concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
		     		CRC.IMAGEN as Imagen,
		        	CRC.CODIGOALFA as CodigoAlfa,
		        	abma.LATITUD as latitud,
        			abma.LONGITUD as longitud,
        			abma.ACTIVO as activo
			   from `dealer_rc` D_Rc
			   inner join abmacodigos as ABMA on ABMA.`ID_RC` = D_Rc.`empresaFk` and D_Rc.objetivo = 1 ";
			   if($iRc!=""){
			   		$SQL.= " and D_Rc.empresaFk = $iRc ";
			   }
		$SQL.= " inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			    LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			    where D_Rc.`dealerFk` = ".$iDealerId." and  (isnull(D_Rc.`caduca`) or D_Rc.`caduca` >= now())
				and ABMA.OBJETIVO = 1 ";
		if(trim($orderBy)){
			$SQL.= " ORDER BY " . $orderBy;
		}
	 	if (!$mysqli->real_query($SQL)){
	       exit();
	    }
	    return BykomClientePhone::getResultado($mysqli);
    }
	/**
	 * Obtengo las cuentas de tipo fijo a partir de las empresas de un dealer 
	 * @param int $iDealerId
	 * @param string $orderBy
	 */
    function getFijosByEmpresasByDealer($iDealerId,$orderBy="id"){
		$mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	    if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	    }
	  
		$SQL= "SELECT abma.order_id as id,
		     		abma.nombre as nombre,
		     		abma.nombre_dos as nombreDos,
		     		abma.codigocl as codigocl,
		     		abma.AVL_PATENTE as patente,
		     		abma.AVL_IDENTIFICADOR as identificador,
		     		concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
		     		CRC.IMAGEN as Imagen,
		        	CRC.CODIGOALFA as CodigoAlfa,
		        	abma.LATITUD as latitud,
        			abma.LONGITUD as longitud,
        			abma.ACTIVO as activo
			   from `dealer_rc` D_Rc
			   inner join abmacodigos as ABMA on ABMA.`ID_RC` = D_Rc.`empresaFk` and D_Rc.objetivo = 1 
				inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			    LEFT JOIN `abrltipoavl` TipoAvl ON ABMA.`AVL_TIPO` = TipoAvl.`ORDER_ID`
			    where D_Rc.`dealerFk` = ".$iDealerId." and  (isnull(D_Rc.`caduca`) or D_Rc.`caduca` >= now())
				and ABMA.OBJETIVO = 1 ";
		if(trim($orderBy)){
			$SQL.= " ORDER BY " . $orderBy;
		}
	 	if (!$mysqli->real_query($SQL)){
	       exit();
	    }
	    return BykomClientePhone::getResultado($mysqli);
    }
	/**
	 * Obtengo las cuentas  a partir de las empresas de un Alias y objetivo 
	 * @param int $iAliasId
	 * @param string $orderBy
	 */
    function getCuentasByEmpresasByAlias($iAliasId,$obj,$orderBy="id"){
		$mysqli = new mysqli(HOST, USER, PASSWORD, DB);
	    if (mysqli_connect_errno()){
	       printf("Conexion fallida: %s\n", mysqli_connect_error());
	       exit();
	    }
	  
		$SQL= "SELECT abma.order_id as id,
		     		abma.nombre as nombre,
		     		abma.nombre_dos as nombreDos,
		     		abma.codigocl as codigocl,
		     		abma.AVL_PATENTE as patente,
		     		abma.AVL_IDENTIFICADOR as identificador,
		     		concat(CRC.CODIGOALFA,'-',abma.ID_CL,'-',cast(abma.particion as char)) as Codigo,
		     		CRC.IMAGEN as Imagen,
		        	CRC.CODIGOALFA as CodigoAlfa,
		        	abma.LATITUD as latitud,
        			abma.LONGITUD as longitud,
        			abma.ACTIVO as activo
			   from `alias_rc` a_Rc
			   inner join abmacodigos as ABMA on ABMA.`ID_RC` = a_Rc.`empresaFk` and a_Rc.objetivo = $obj 
				inner join rcmacodigos as CRC on CRC.`ORDER_ID` = ABMA.id_rc
			    where a_Rc.`aliasFk` = ".$iAliasId." and  (isnull(a_Rc.`caduca`) or a_Rc.`caduca` >= now())
				and ABMA.OBJETIVO = $obj ";
		if(trim($orderBy)){
			$SQL.= " ORDER BY " . $orderBy;
		}
	 	if (!$mysqli->real_query($SQL)){
	       exit();
	    }
	    return BykomClientePhone::getResultado($mysqli);
    }
} 
?>